package shuai.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import shuai.model.User;
import shuai.service.IUserService;
@Controller
@RequestMapping("/user")
public class UserController {
	
	@Resource
	private IUserService userService;
	
	@RequestMapping("/userlist")
	public String findAll(Model model){
		List<User> list=userService.selectAll();
		model.addAttribute("list",list);
		return "list";
	}
	
	@RequestMapping("/showUser")
	public String toIndex(HttpServletRequest request,Model model){
		int userId=Integer.parseInt(request.getParameter("id"));
		User user=userService.selectByPrimaryKey(userId);
		model.addAttribute("user",user);
		return "showUser";
	}
	
	@RequestMapping("/allUser")
	public String toAll(HttpServletRequest request,Model model){
		List<User> users=userService.selectAll();
		model.addAttribute("users",users);
		return "allUser";
	}
	
	//访问/user/toaddUser才能添加
	@RequestMapping("/toaddUser")
	public String toAddUser(){
		return "addUser";
	}
	
	@RequestMapping("/addUser")
	public String addUser(HttpServletRequest request,Model model){
		String name=request.getParameter("username");
		String pwd=request.getParameter("password");
		int age= Integer.parseInt(request.getParameter("age"));
		
		User user=new User();
		user.setUsername(name);
		user.setPassword(pwd);
		user.setAge(age);
		
		userService.addUser(user);
		
		return "redirect:/user/allUser";
	}
	
	@RequestMapping("/delUser")
	public String delUser(HttpServletRequest request,Model model){
		int id=Integer.parseInt(request.getParameter("id"));
		int flag=userService.delUser(id);
		if (flag>0) {
			return "redirect:/user/allUser";
		}else{
			model.addAttribute("msg","删除失败");
			return "redirect:/user/allUser";
		}
		
	}
	
	
	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	
	
}
